from django.shortcuts import render

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404

from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.views import APIView

from Ws.models import Noticia
from Ws.serializers import NoticiaSerializer

# Create your views here.



# Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt
# @csrf_exempt
# def lista_noticias(request):
#     if request.method == 'GET':
#         noticias = Noticia.objects.all()
#         serializer = NoticiaSerializer(noticias, many=True)
#         return JsonResponse(serializer.data, safe=False)


@api_view(['GET'])
@permission_classes((permissions.AllowAny,)) # parece ser necesario segun https://stackoverflow.com/questions/31335736/cannot-apply-djangomodelpermissions-on-a-view-that-does-not-have-queryset-pro
def lista_noticias(request):
    if request.method == 'GET':
        noticias = Noticia.objects.all()
        serializer = NoticiaSerializer(noticias, many=True)
        return Response(serializer.data)
    
# @csrf_exempt
# def snippet_list(request):
#     """
#     List all code snippets, or create a new snippet.
#     """
#     if request.method == 'GET':
#         snippets = Snippet.objects.all()
#         serializer = SnippetSerializer(snippets, many=True)
#         return JsonResponse(serializer.data, safe=False)

#     elif request.method == 'POST':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JsonResponse(serializer.data, status=201)
#         return JsonResponse(serializer.errors, status=400)


@api_view(['GET'])
def detalles_noticia(request, id):

    try:
        noticia = Noticia.objects.get(pk=int(id))
    except Noticia.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        serializer = NoticiaSerializer(noticia)
        return Response(serializer.data)


class ListaNoticias(APIView):
    '''
    Listar todas las noticias
    '''
    def get(self, request, format=None):
        noticias = Noticia.objects.all()
        serializer = NoticiaSerializer(noticias, many=True)
        return Response(serializer.data)

class DetalleNoticia(APIView):
    def get_object(self, id):
        try:
            return Noticia.objects.get(pk=int(id))
        except Noticia.DoesNotExist:
            raise Http404

    def get(self, request, id, format=None):
        noticia = self.get_object(id)
        serializer = NoticiaSerializer(noticia)
        return Response(serializer.data)


    

